import {
  // eslint-disable-next-line no-unused-vars
  IProduct,
  // eslint-disable-next-line no-unused-vars
  TNetworkConfigTypeEnu,
  // eslint-disable-next-line no-unused-vars
  IConfigDeviceTips,
} from '@/config/product';

interface IConfigListener {
  deviceListChange?: (deviceList: IDevice[]) => void; // 配网过程中设备回调
  deviceChange?: (device: IDevice) => void; // 配网过程中设备回调
  timeOutEevnt?: () => void; // 配网超时回调
  configFail?: () => void; // 配网失败回调
}

export interface IConfigNetworkParam {
  wifiName: string; // 配网wifi名称
  password: string; // 配网wifi 密码
  timeout?: number; // 配网超时时间
  listener?: IConfigListener;
  [propName: string]: any; // 其他自定义属性
}

export interface IBaseConfigNetworkInitProps {
  productConfig: IProduct;
}

export interface IBaseConfigNetworkProps extends IBaseConfigNetworkInitProps {
  productConfig: IProduct;
  type: TNetworkConfigTypeEnu;
  configTips: IConfigDeviceTips | undefined;
  // 是否需要wifi名称，默认需要
  needWifiName: () => boolean;
  // 是否需要wifi password，默认需要
  needWifiPassword: () => boolean;
  // 开始配网
  startConfig: (param?: IConfigNetworkParam) => Promise<any>;
  // 结束配网
  endConfig: () => void;
}

// 配网抽象类，这个类不能直接使用，只能等子类继承，实现自己的配网流程与方法，使用子类
export default class BaseConfigNetwork implements IBaseConfigNetworkProps {
  _listener?: IConfigListener; // 配网过程事件回调

  _timeoutTimer?: any;

  productConfig: IProduct;

  type: TNetworkConfigTypeEnu;

  configTips: IConfigDeviceTips | undefined;

  constructor(props: IBaseConfigNetworkInitProps) {
    const { productConfig } = props;
    this.productConfig = productConfig;
    this.configTips = undefined;
  }

  needWifiName() {
    return true;
  }

  needWifiPassword() {
    return true;
  }

  // 子类必须实现
  async startConfig(param?: IConfigNetworkParam) {
    console.log('super startConfig');
    if (param) {
      const { timeout, listener } = param;
      if (timeout) {
        this.clearTimeoutTimer();
        this._timeoutTimer = setTimeout(this.timeoutHandle, timeout);
      }
      if (listener) {
        this._listener = listener;
      }
    }
    return {};
  }

  // 子类必须实现
  endConfig() {
    this.clearTimeoutTimer();
  }

  timeoutHandle() {
    console.log('timeoutHandle');
    if (this._listener && this._listener.timeOutEevnt) {
      this._listener.timeOutEevnt();
    }
  }

  clearTimeoutTimer() {
    clearTimeout(this._timeoutTimer);
    this._timeoutTimer = null;
  }
}
